import axios, { type AxiosResponseHeaders } from 'axios'
// 引入 NProgress
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// import useUserInfoStore from '../stores/modules/shopCart'

/**
 * 前台项目axios封装
 */

//手机号正则
export const phoneReg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/

// 验证码正则
export const codeReg = /^\d{6}$/

// 密码正则
export const pwdReg = /^\w{6,21}$/
// 新建一个axios实例
const request = axios.create({
  baseURL: '/front-dev',
  timeout: 10000
})

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    // let token = useUserInfoStore().token
    let token = localStorage.getItem('token_key')
    // console.log(token);

    if (token) {
      ;(config.headers as AxiosResponseHeaders).token = token
    }
    // 开启进度条
    NProgress.start()
    // 从本地储存中获取token
    // 如果 token 存在，证明用户成功登录过
    if (token) {
      //@ts-ignore
      config.headers.token = token || ''
    }
    config.headers.userTempId = localStorage.getItem('token_key')
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    if (response.data.code === 208) {
      window.location.href = '/login'
    } else {
      // 对返回的数据进行简化操作
      NProgress.done()
      // console.log(111);

      return response.data
    }
  },
  (error) => {
    alert(error.message)
    return new Promise(() => {})
  }
)
export default request
